package cn.middle.edge.portal;

import java.util.Date;
import java.util.List;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.middle.common.basic.enums.Status;
import com.middle.common.result.ApiResponse;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.middle.basic.entity.SysMenu;
import cn.middle.basic.service.SysMenuService;

/**
 * 菜单权限管理
 * @author KING
 *
 */
@RequestMapping("/menu")
@Controller
public class MenuController {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	private final static String PREFIX = "sys/menu/";
	
	@Autowired
	private SysMenuService menuService;
	
	@SaCheckPermission("menu:list")
	@GetMapping("/list")
	public String list(){
		return PREFIX + "list";
	}
	
	@SaCheckPermission("menu:list")
	@ResponseBody
	@GetMapping("/ajaxList")
	public ApiResponse<List<SysMenu>> ajaxList(String name){
		return ApiResponse.successWithData(menuService.list(name));
	}
	
	@SaCheckPermission("menu:add")
	@ResponseBody
	@PostMapping("/add")
	public ApiResponse<String> add(@Valid SysMenu menu) {
		menu.setCreateTime(new Date());
		menu.setUpdateTime(new Date());
		menu.setStatus(Status.Active.code());
		menuService.save(menu);
		return ApiResponse.successWithData("新增菜单成功！");
	}
	
	@SaCheckPermission("menu:delete")
	@GetMapping("/delete")
	@ResponseBody
	public ApiResponse<String> delete(@NotNull(message="id 不能为空！")Long id){
		logger.info("delete menuId = {}",id);
		menuService.deleteBySysId(id);
		return ApiResponse.successWithData("删除成功！");
	}
	
	@SaCheckPermission("menu:add")
	@GetMapping("/add")
	public String add() {
		return PREFIX +"add";
	}
	
	@SaCheckPermission("menu:edit")
	@ResponseBody
	@PostMapping("/edit")
	public ApiResponse<String> edit(@Valid SysMenu menu) {
		menu.setUpdateTime(new Date());
		this.menuService.update(menu);
		return ApiResponse.successWithData("更新菜单成功！");
	}
	
	@SaCheckPermission("menu:edit")
	@GetMapping("/edit")
	public String edit(@NotNull(message="id 不能为空！")Long id,ModelMap modelMap) {
		modelMap.put("menu", menuService.getById(id));
		return PREFIX +"edit";
	}
	@SaCheckLogin
	@ResponseBody
	@GetMapping("/menuTypeList")
	public ApiResponse<List<SysMenu>> findByMenuType(@NotNull(message="菜单类型不能为空！")Byte menuType){
		List<SysMenu> list = menuService.menuTypeList(menuType);
		return ApiResponse.successWithData(list);
	}
	

}
